package cn.apestar.common.chat.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSONObject;

public class HttpUtil {

    private static final long serialVersionUID = -8483811141908827663L;

    private static final int TIMEOUT_SECONDS = 200;

    private static final String POST = "POST";

    private static final String GET = "GET";

    private static HttpClient httpClient = null;

    /**
     * 取得HTTPCLIENT 实列
     * @return
     */
    public static HttpClient getHttpClient() {

        HttpClient httpClient = null;
        if (httpClient == null) {
            httpClient = new DefaultHttpClient();
            httpClient = WebClientDevWrapper.wrapClient(httpClient);
            HttpParams httpParams = httpClient.getParams();
            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SECONDS * 1000);
        }
        return httpClient;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String executionPost(String url, List<BasicNameValuePair> formparams, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(url);
        if (token != null) {
            post.addHeader("Authorization", token); // 认证token
        }
        post.addHeader("Content-Type", "application/json"); // 认证token
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(uefEntity);
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        // if(remoteResponse.getStatusLine().getStatusCode() != 200 &&
        // remoteResponse.getStatusLine().getStatusCode() != 302){
        // throw new RuntimeException("连接失败");
        // }
        entity = remoteResponse.getEntity();
        System.out.println(entity.getContent());
        String endResponseString = getStringAsStream(entity.getContent());
        return endResponseString;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String executionPost(String url, Object formparams, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(url);
        if (token != null) {
            post.addHeader("Authorization", token); // 认证token
        }
        post.addHeader("Content-Type", "application/json"); // 认证token
        String s = formparams.toString();
        StringEntity se = new StringEntity(formparams.toString(), "utf-8");
        post.setEntity(se);
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        entity = remoteResponse.getEntity();
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            // throw new BaseException(endResponseString);
        }
        return endResponseString;
    }

    /**
     * 同步执行GET传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String executionGET(String url, List<BasicNameValuePair> formparams, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpGet get = new HttpGet(url);
        if (token != null) {
            get.addHeader("Authorization", token); // 认证token
        }
        get.addHeader("Content-Type", "application/json"); // 认证token
        if (formparams != null && formparams.size() > 0) {
            url = url + "&" + URLEncodedUtils.format(formparams, HTTP.UTF_8);
        }

        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(get);

        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            throw new RuntimeException("连接失败");
        }
        entity = remoteResponse.getEntity();
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        return endResponseString;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String executionDel(String url, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpDelete post = new HttpDelete(url);
        if (token != null) {
            post.addHeader("Authorization", token); // 认证token
        }
        post.addHeader("Content-Type", "application/json"); // 认证token
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        entity = remoteResponse.getEntity();
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302
            && remoteResponse.getStatusLine().getStatusCode() != 401) {
            throw new RuntimeException("连接失败");
        }

        return endResponseString;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static void executionAsycPost(String url, JSONObject formparams, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(url);
        post.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "utf-8");
        post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");
        if (token != null) {
            post.addHeader("Authorization", token); // 认证token
        }
        post.addHeader("Content-Type", "application/json;charset=utf-8;"); // 认证token

        StringEntity se = new StringEntity(formparams.toString(), "utf-8");
        post.setEntity(se);

        HttpClient client = getHttpClient();
        client.execute(post);
    }

    /**
     * 取得传输参数
     * @return
     */
    public static List<BasicNameValuePair> getBasicNameValuePair(Map map) {

        List<BasicNameValuePair> formparams = new ArrayList<>();

        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            formparams.add(new BasicNameValuePair(s, (String) map.get(s)));
        }

        return formparams;
    }

    /**
     * 对流进行转化
     * @param ins
     * @return
     */
    public static String getStringAsStream(InputStream ins) {

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuffer sbf = new StringBuffer();
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        /** 回收资源 */
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = sbf.toString();
        return s;
    }

    public static boolean getResult(String action) {

        return action.contains("error");
    }

}